package tools

import (
	"encoding/csv"
	"fmt"
	"os"
)

func WriteCsv(filename string, header []string, records [][]string) error {

	// 创建csv文件
	file, err := os.Create(filename + ".csv")
	if err != nil {
		return fmt.Errorf("Error creating file:", err)

	}
	defer file.Close()

	// Add BOM for UTF-8 encoding
	_, _ = file.WriteString("\xEF\xBB\xBF")

	// 创建新的csv writer
	writer := csv.NewWriter(file)
	defer writer.Flush() // 确保所有数据都被写入文件

	// 写入CSV头部
	err = writer.Write(header)
	if err != nil {
		return fmt.Errorf("Error writing record to file:", err)
	}

	for _, record := range records {
		err := writer.Write(record)
		if err != nil {
			return fmt.Errorf("Error writing record to file:", err)
		}
	}
	return nil
}
